// 版权归 瞄你个汪 所有。使用本代码应遵守相关法律法规和Apache 2.0开源许可要求。
package top.geeke.toolkit.supertable.core;

import org.springframework.util.ObjectUtils;
import top.geeke.toolkit.supertable.annotation.SuperColumn;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * <p>
 *  字段值校验关联类
 * </p>
 *
 * @author 瞄你个汪
 * @since 2024/6/3 9:09
 */
public class SuperColumnValidator implements ConstraintValidator<SuperColumn, Object> {
    private boolean nullable;
    private String comment;
    private int length;

    @Override
    public void initialize(SuperColumn constraintAnnotation) {
        this.comment = constraintAnnotation.value();
        this.nullable = constraintAnnotation.nullable();
        this.length = constraintAnnotation.length();
    }

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {
        if (!this.nullable && ObjectUtils.isEmpty(object)) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(String.format("\"%s\"不能为空", this.comment))
                    .addConstraintViolation();
            return false;
        }
        if (object instanceof String && object.toString().length() > this.length) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(String.format("\"%s\"字符长度不能超过%d位", this.comment, this.length))
                    .addConstraintViolation();
            return false;
        }
        return true;
    }
}
